using System.Text;
using Newtonsoft.Json.Linq;

namespace MyEsAPI;

public class ElasticsearchService
{
    private readonly HttpClient _httpClient;
    private readonly string _baseUrl;
    private readonly string _username;
    private readonly string _password;

    public ElasticsearchService(
        string baseUrl = "http://192.168.3.208:19200",
        string username = "ris_admin",
        string password = "hinacom"
    )
    {
        _baseUrl = baseUrl;
        _username = username;
        _password = password;

        _httpClient = new HttpClient();

        // 设置基本认证
        var authToken = Convert.ToBase64String(Encoding.UTF8.GetBytes($"{_username}:{_password}"));
        _httpClient.DefaultRequestHeaders.Authorization =
            new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", authToken);
    }

    // 执行搜索查询
    public async Task<JObject> SearchAsync(string indexName, string queryJson)
    {
        var url = $"{_baseUrl}/{indexName}/_search";
        var content = new StringContent(queryJson, Encoding.UTF8, "application/json");

        var response = await _httpClient.PostAsync(url, content);
        response.EnsureSuccessStatusCode();

        var responseContent = await response.Content.ReadAsStringAsync();
        return JObject.Parse(responseContent);
    }

    // 执行聚合查询
    public async Task<JObject> AggregateAsync(string indexName, string aggregationJson)
    {
        var url = $"{_baseUrl}/{indexName}/_search";
        var content = new StringContent(aggregationJson, Encoding.UTF8, "application/json");

        var response = await _httpClient.PostAsync(url, content);
        response.EnsureSuccessStatusCode();

        var responseContent = await response.Content.ReadAsStringAsync();
        return JObject.Parse(responseContent);
    }
}
